package com.hongyuan.venue.ui.main.view_mode;

import android.app.Application;

import androidx.annotation.NonNull;

import com.hongyuan.venue.base.CustomViewModel;
import com.hongyuan.venue.data.Constants;
import com.hongyuan.venue.data.MyRepository;
import com.hongyuan.venue.data.userbean.MemberLoginBean;
import com.hongyuan.venue.data.userbean.TokenBean;
import com.hongyuan.venue.data.userbean.TokenSingleBean;
import com.hongyuan.venue.ui.main.activity.CodeLoginActivity;
import com.hongyuan.venue.ui.main.activity.MainActivity;
import com.hongyuan.venue.utils.HourMeterUtil;

public class StartupPageViewModel extends CustomViewModel<MyRepository> implements HourMeterUtil.TimeCallBack {

    //计时3秒进入主界面
    private HourMeterUtil hourMeterUtil;

    //是否需要跳转到登录页面
    private boolean isLogin = false;

    public StartupPageViewModel(@NonNull Application application, MyRepository model) {
        super(application, model);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        //初始化计时对象
        hourMeterUtil = new HourMeterUtil();
        hourMeterUtil.setTimeCallBack(this);

    }

    @Override
    public void onResume() {
        super.onResume();

        //启动计时
        hourMeterUtil.startCount();
    }

    @Override
    public void onDestroy() {
        //销毁计时
        hourMeterUtil.onDestory();
        super.onDestroy();
    }

    @Override
    protected void returnData(int code, Object dataBean) {
        super.returnData(code, dataBean);

        if(code == Constants.GET_TOKEN){
            TokenBean bean = (TokenBean) dataBean;
            //保存用户token信息
            model.saveToken(bean);

            //去设置应用需要使用的token信息
            if(userToken == null){
                userToken = TokenSingleBean.getInstance();
            }
            userToken.setAt_id(bean.getAt_id());
            userToken.setAt_name(bean.getAt_name());
            userToken.setAt_pwd(bean.getAt_pwd());
            userToken.setToken(bean.getToken());

            //是否登录过
            MemberLoginBean loginBean = model.getUser();

            if(loginBean != null && loginBean.getM_mobile() != null){
                userToken.setM_id(loginBean.getM_id());
                userToken.setM_mobile(loginBean.getM_mobile());
                userToken.setRole_id(String.valueOf(loginBean.getRole_id()));
                //设置已登录过
                isLogin = true;
            }
        }
    }

    @Override
    public void onTime(int passedTime) {
        if(passedTime == 3){
            //停止计时
            hourMeterUtil.stopCount();
            //暂时调整到登录页面处理
            if(isLogin){
                startActivity(MainActivity.class);
            }else{
                startActivity(CodeLoginActivity.class);
            }
            //关闭页面
            finish();
        }
    }
}
